package 二叉树;


/**
 * https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
 *
 * 题解：https://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247493359&idx=1&sn=9652f7cb54cdcab2b04891a48e0b2bfd&chksm=9bd418e7aca391f161331678018c7f5e6e4ad166c0a64e930bd43a9e06d7c6742e7cd0fabd46&scene=178&cur_album_id=2165089327943417857#rd
 */
public class _106_从中序与后序遍历虚了构造二叉树 {

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return buildTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
    }

    private TreeNode buildTree(int[] inorder, int istart, int iend, int[] postorder, int pstart, int pend) {
        if (istart > iend || pstart > iend) return null;

        int rootValue = postorder[pend];
        TreeNode root = new TreeNode(rootValue);

        int index = 0;
        // 这边遍历不是从istart到iend了
        for (int i = 0; i < inorder.length; i++) {
            if (rootValue == inorder[i]) {
                index = i;
                break;
            }
        }

        root.left = buildTree(inorder, istart, index - 1, postorder, pstart, pstart + (index - istart)-1);
        root.right = buildTree(inorder, index + 1, iend, postorder, pstart + (index - istart), pend - 1);

        return root;
    }
}
